package com.example.plantuml.demo.repository;

import com.example.plantuml.demo.model.User;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

@Repository
public class UserRepository {
    private final Map<Long, User> users = new HashMap<>();
    private final AtomicLong sequence = new AtomicLong(1);
    
    public Optional<User> findById(Long id) {
        // 模拟数据库查询延迟
        simulateDelay(100);
        return Optional.ofNullable(users.get(id));
    }
    
    public User save(User user) {
        // 模拟数据库操作延迟
        simulateDelay((int)(Math.random()*1000));
        if (user.getId() == null) {
            user.setId(sequence.getAndIncrement());
        }
        users.put(user.getId(), user);
        return user;
    }
    
    public Iterable<User> findAll() {
        // 模拟数据库查询延迟
        simulateDelay(200);
        return users.values();
    }
    
    // 模拟处理延迟
    private void simulateDelay(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
